//
//  CXLAFNMangerTool.swift
//  Swift封装AFN网络管理者
//
//  Created by 曹晓龙 on 15/10/15.
//  Copyright © 2015年 曹晓龙. All rights reserved.
//

import UIKit
//import AFNetworking

import Alamofire

///  发送网络请求的方式
///
///  - GET:  GET
///  - POST: POST
//enum CXLMethodType:String{
//    case GET
//    case POST
//}

/// 单例
class CXLAFNMangerTool{

    /// 单例
    static let sharedAFNMangerTool = CXLAFNMangerTool()
        
//    {
//        
//        let tools = CXLAFNMangerTool(baseURL: NSURL(string: "http://www.weather.com.cn/"))
//        
//        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
//        
//        return tools
//    }()
    
    /// 定义block
    typealias AFNFinishBlock = (result:AnyObject?, error:NSError?)->()
    
    /// 申请应用时分配的AppKey
    let client_id = "3205166051"
    /// 授权回调地址，站外应用需与设置的回调地址一致，站内应用需填写canvas page的地址
    let redirect_uri = "http://www.baidu.com"
    /// 申请应用时分配的AppSecret
    let client_secret = "d2319b8ad9c1840af79a74b3176e7d04"
    
}

// MARK: - 发布微博
extension CXLAFNMangerTool {
    
    ///  发布微博
    ///
    ///  - parameter status:      传入文本内容
    ///  - parameter finishBlock: 完成回调
    func updateStatus(status:String,image:UIImage?, finishBlock:AFNFinishBlock){

        
        var parameters = [String : AnyObject]()
        
        parameters["status"] = status
        
        if image == nil {
            
            let urlString = "https://api.weibo.com/2/statuses/update.json"

            
            tokenRequest(.POST, urlString: urlString, parameters: parameters, finishBlock: finishBlock)
            
        }else{
            
            let data = UIImagePNGRepresentation(image!)
            
             let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            
            upload(urlString, parameters: parameters, data: data!, name: "pic", finishBlock: finishBlock)
        }
        
    }
    
}

// MARK: - 加载微博首页数据
extension CXLAFNMangerTool {
    
    ///  加载微博主页数据
    ///  - parameter since_id 若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
    ///  - parameter max_id 若指定此参数，则返回ID小于或等于max_id的微博，默认为0。
    ///  - parameter finishedBlock: 完成回调
    func loadHomeInfo(since_id since_id:Int, max_id:Int, finishedBlock:AFNFinishBlock){

        var parameters = [String : AnyObject]()
        
        if max_id > 0{// 上拉
            
            parameters["max_id"] = max_id - 1
            
        }else{//下拉
            
            parameters["since_id"] = since_id
        }
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        tokenRequest(.GET, urlString: urlString, parameters: parameters, finishBlock: finishedBlock)
    }
}

// MARK: - 加载用户信息
extension CXLAFNMangerTool {
    
    ///  加载用户信息
    ///
    ///  - parameter uid:         uid
    ///  - parameter token:       授权令牌
    ///  - parameter finishBlock: 回调
    func getUserInfo(uid:String, finishBlock:AFNFinishBlock){

        
        var parameters = [String : AnyObject]()
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        parameters["uid"] = uid
        
        tokenRequest(.GET, urlString: urlString, parameters: parameters, finishBlock: finishBlock)
    }
}

// MARK: - 获取授权令牌
extension CXLAFNMangerTool {
    
    ///  获取授权令牌
    ///
    ///  - parameter code:        授权码
    ///  - parameter finishBlock: 回调
    func getToken(code:String, finishBlock:AFNFinishBlock){
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let parameters = ["client_id":client_id,
                          "redirect_uri":redirect_uri,
                          "client_secret":client_secret,
                          "code":code,
                          "grant_type":"authorization_code"]
        request(.POST, urlString: urlString, parameters: parameters, finishBlock: finishBlock)
        
    }
}

// MARK: - OAuth授权界面相关
extension CXLAFNMangerTool {
    /// 授权页面的URL
    var oauthUrl:NSURL{
        
        return NSURL(string: "https://open.weibo.cn/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)")!
    }
}


// MARK: - 封装工具类的下载方法
extension CXLAFNMangerTool {
    
    ///  将token封装到字典中
    ///
    ///  - parameter parameters: 上传数据时携带的参数字典
    ///
    ///  - returns: true: 封装成功,fale 添加失败
    private func getParameters(inout parameters: [String: AnyObject]?) -> Bool {
        
        guard let token = OauthViewModel.sharedOauthViewModel.access_token else{
            
            return false
        }
        
        if parameters == nil {
            
            parameters = [String : AnyObject]()
        }
        
        parameters!["access_token"] = token
 
        
        return true
    }
    
    ///  封装发送带token的网络请求
    ///
    ///  - parameter methodType:  请求类型
    ///  - parameter urlString:   urlString
    ///  - parameter parameters:  传入参数字典
    ///  - parameter finishBlock: 回调
    func tokenRequest(methodType:Alamofire.Method, urlString:String, var parameters: [String: AnyObject]?, finishBlock:AFNFinishBlock){
        
        if !getParameters(&parameters) {
            
            finishBlock(result: nil, error: NSError(domain: "xxx", code: -1000, userInfo: ["message":"token已过期"]))

            
            return
        }
        
        request(methodType, urlString: urlString, parameters: parameters, finishBlock: finishBlock)
    }
    
    ///  上传带图片的网络请求
    ///
    ///  - parameter urlString:   字符串
    ///  - parameter parameters:  参数字典
    ///  - parameter data:        数据
    ///  - parameter name:        服务器规定的参数名
    ///  - parameter finishBlock: 回调
    func upload(urlString:String, var parameters:[String: AnyObject]?, data:NSData, name:String, finishBlock:AFNFinishBlock){
        
        if !getParameters(&parameters) {
            
            finishBlock(result: nil, error: NSError(domain: "xxx", code: -1000, userInfo: ["message":"token已过期"]))
            
            
            return
        }
        
        Alamofire.upload(.POST, urlString, multipartFormData: { (formData) -> Void in
            
            formData.appendBodyPart(data: data, name: name, fileName: "xxxx", mimeType: "application/octet-stream")
            
            if let parameters = parameters {
                
                for (k, v) in parameters{
                    
                    let str = v as! String
                    
                    let strData = str.dataUsingEncoding(NSUTF8StringEncoding)
                    
                    formData.appendBodyPart(data: strData!, name: k)
                }
            }
            
            }, encodingMemoryThreshold: 5 * 1024 * 1024) { (encodingResult) -> Void in
                
                switch encodingResult{
                    
                case.Success(let upload, _, _):
                    
                    upload.responseJSON { response in

                        if response.result.isFailure{
                            QL4Error("加载数据错误\(response.result.error)")
                            return
                        }
                        finishBlock(result: response.result.value, error:response.result.error )
                    }
                case .Failure(let encodingError):

                    QL4Error("拼接数据错误\(encodingError)")
                }
        }
    }
    
    ///  封装的发送AFN网络请求的方法
    ///
    ///  - parameter methodType:  请求类型
    ///  - parameter urlString:   urlString
    ///  - parameter parameters:  传入参数字典
    ///  - parameter finishBlock: 回调
    func request(methodType: Alamofire.Method, urlString:String, parameters: [String: AnyObject]?, finishBlock:AFNFinishBlock){
        
        Alamofire.request(methodType, urlString, parameters: parameters).responseJSON { (response) -> Void in
            if response.result.isFailure{
                QL4Error("数据错误\(response.result.error)")
                return
            }
            finishBlock(result: response.result.value, error:response.result.error )
        }
    }
}